/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.easyjava.restlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.routing.Filter;

/**
 *
 * @author 朱雀
 */
public class JsonPackFilter extends Filter {

	public JsonPackFilter(Context context) {
		super(context);
	}

	public JsonPackFilter() {
	}

	@Override
	protected void afterHandle(Request request, Response response) {
		String jpf = request.getResourceRef().getQueryAsForm().getFirstValue("callback");
		if (jpf != null) {
			StringBuilder sb = new StringBuilder(jpf);
			sb.append('(');
			Status status = response.getStatus();
			if (status.getCode() >= 300) {
				sb.append("{code:").append(status.getCode()).append(",msg:")
						.append(status.getDescription().replace("'", "\\'")).append("'}");
				response.setStatus(status.SUCCESS_OK);
			} else {
				Representation representation = response.getEntity();
				if (representation != null) {
					try {
						InputStream is = representation.getStream();
						if (is != null) {
							ByteArrayOutputStream baos = new ByteArrayOutputStream();
							byte[] buf = new byte[0x10000];
							int len;
							while ((len = is.read(buf)) > 0) {
								baos.write(buf, 0, len);
							}
							sb.append(baos.toString("UTF-8"));
						} else {
							response.setStatus(status.SERVER_ERROR_INTERNAL, "NullPointer in JPF Filter");
						}
					} catch (IOException e) {
						response.setStatus(status.SERVER_ERROR_INTERNAL, e.getMessage());
					}
				}
			}
			sb.append(");");
			response.setEntity(new StringRepresentation(sb.toString(), MediaType.TEXT_JAVASCRIPT));
		}
	}

}
